package com.oa.kq.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.service.BaseService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.kq.entity.Dept;
import com.oa.kq.entity.GroupDept;
import com.oa.kq.mapper.DeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Service
public class DeptService extends BaseService<DeptMapper, Dept> {
    static Logger logger = LoggerFactory.getLogger(DeptService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }

//    @DS("adm-ds")
//    @Override
//    public List<Map<String, Object>> selectListMapByWhere(Map<String, Object> parameter) {
//        return super.selectListMapByWhere(parameter);
//    }
//
//    @DS("adm-ds")
//    @Override
//    public <T> T selectOneObject(T parameter) {
//        return super.selectOneObject(parameter);
//    }
//
//    @DS("adm-ds")
//    @Override
//    public <T> int deleteByPk(T parameter) {
//        return super.deleteByPk(parameter);
//    }
//
//    @DS("adm-ds")
//    @Override
//    public <T> int[] batchDelete(List<T> batchValues) {
//        return super.batchDelete(batchValues);
//    }

    /**
     * 获取根部门，子部门及其员工信息
     *
     * @return
     */
    @DS("adm-ds")
    public Map<String, Object> getDeptInfo(Dept dept) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<>();

        Dept rootDept = new Dept();// 查询除了的部门
        if ("-1".equals(dept.getDeptid())) {
            User user = LoginUtils.getCurrentUserInfo();
            dept.setDeptid(user.getDeptid());
            // 查询最顶级部门
            rootDept = baseMapper.selectTopDept(dept);
        } else {
            rootDept = this.selectOneObject(dept);//
        }
        map.put("rootDept", rootDept);//获取根节点 或者是某一个节点的部门编号


        // 查询该部门下的父节点，包括祖宗
        List<Dept> ancestorList = baseMapper.selectAncestorByDeptid(rootDept);//向上
        map.put("ancestorList", ancestorList);//查询祖先


        // 查询该部门下的子部门。不包括孙子
        List<Dept> deptList = baseMapper.selectChildrenByDeptid(rootDept);
        // 查询每个部门包含的人数
        Map<String, Object> condition = new HashMap<>();
        for (int i = 0; i < deptList.size(); i++) {
            condition.put("deptid", deptList.get(i).getDeptid());
            List<Map<String, Object>> selectList = baseMapper.selectListMapByWhere(null, null, condition);
            Map<String, Object> deptmap = new HashMap<>();
            deptmap.put("dept", deptList.get(i));
            deptmap.put("deptNum", selectList.size());
            listMap.add(deptmap);
        }
        map.put("listMap", listMap);
        // 查询该部门下的员工
        condition.put("deptid", rootDept.getDeptid());
//        List<Map<String, Object>> rootMember = this.selectList("selectListByDepartId", condition);
        List<Map<String, Object>> rootMember = baseMapper.selectListMapByWhere(null, null, condition);
        for (int i = 0; i < rootMember.size(); i++) {
            if (rootMember.get(i).get("HEADIMGURL") == null) {
                rootMember.get(i).put("HEADIMGURL", rootMember.get(i).get("THEADIMGURL"));
            }
        }
        map.put("rootMember", rootMember);
        return map;
    }


    /**
     * 部门和成员信息    拓展
     * 获取当前部门的信息（成员）
     * 当前部门的子部门（不包括孙子）的（成员，名字）
     *
     * @author LinYuKun
     * @cdate 2020/01/04 15:09
     */

    @DS("adm-ds")
    public Map<String, Object> deptMemberInfoExt(Dept dept) {
        Map<String, Object> map = new HashMap<String, Object>();//创建对象

        Dept currentDept = new Dept();// //用来存储当前部门的信息

        List<Map<String, Object>> rootMember = new ArrayList();//用来存储当前部门的用户信息

        List<Map<String, Object>> childMapArr = new ArrayList<>();//用来存储子部门和子部门的用户的信息

        if ("-1".equals(dept.getDeptid())) {
            User user = LoginUtils.getCurrentUserInfo();
            dept.setDeptid(user.getDeptid());
            currentDept = this.selectOneObject(dept);
        } else {
            currentDept = this.selectOneObject(dept);
        }

        if (!ObjectUtils.isEmpty(currentDept) && !StringUtils.isEmpty(currentDept.getDeptid())) {
//            rootMember = this.selectList("selectUserByDeptId", currentDept);//根据部门id查询用户
            rootMember = baseMapper.selectUserByDeptId(currentDept);

            List<Dept> deptList = baseMapper.selectChildrenByDeptid(currentDept);//查询子部门

            Map<String, Object> condition = new HashMap<>();//防止循环的时候 创建过多对象

            for (int i = 0; i < deptList.size(); i++) {//遍历子部门
                condition.put("deptid", deptList.get(i).getDeptid());
                /*根据部门id查询该部门下的用户以及子部门和孙子部门的用户数量*/
                /*selectCurrentDeptUserAndChildAndGrandSonByDeptid*/
                List<Map<String, Object>> selectList = baseMapper.selectCurrentDeptUserAndChildAndGrandSonByDeptid(condition);
                Map<String, Object> deptmap = new HashMap<>();
                deptmap.put("dept", deptList.get(i));
                deptmap.put("deptUserList", selectList);
                deptmap.put("deptUserNum", selectList.size());
                childMapArr.add(deptmap);
            }
        }

        map.put("rootDept", currentDept);//当前部门的信息

        map.put("rootMember", rootMember);//当前部门的成员信息

        map.put("childMapArr", childMapArr);//子部门的集合

        return map;
    }

    /**
     * 获取该公司下的所有部门。用于添加子部门时，提供选择。
     *
     * @return
     */

    @DS("adm-ds")
    public List<Dept> getAllDept(String deptid) {
        Dept dept = new Dept();
        dept.setDeptid(deptid);
        // 1.先查出根节点
        Dept rootDept = baseMapper.selectTopDept(dept);
        // 2.根据根节点查出所有后代节点
        return baseMapper.selectOffspringByDeptid(rootDept);
    }

    /**
     * 获取某个部门的上级部门 用于设置部门时，显示上级部门
     *
     * @return
     */

    @DS("adm-ds")
    public Dept getFatherDept(String deptid) {
        Dept dept = new Dept();
        dept.setDeptid(deptid);
        return baseMapper.selectFatherByDeptid(dept);
    }

    /**
     * 判断该部门是否有成员。或者是否有子部门。 用于判断是否可以删除该部门
     *
     * @return
     */

    @DS("adm-ds")
    public boolean isDeleteDept(String deptid) {
        Dept dept = new Dept();
        dept.setDeptid(deptid);
        Map<String, Object> condition = new HashMap<>();
        condition.put("deptid", deptid);
        // 判断该部门是否有成员。
//        List<Map<String, Object>> member = this.selectList("selectListByDepartId", condition);
        List<Map<String, Object>> member = baseMapper.selectListMapByWhere(null, null, condition);
        // 判断该部门是否有子部门
        List<Dept> deptList = baseMapper.selectChildrenByDeptid(dept);
        if (member.size() > 0 || deptList.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取该公司除了自己子代以外的所有部门。用于设置子部门时，提供选择。 设置子部门时，不能选自己的子代或者孙子
     *
     * @return
     */

    @DS("adm-ds")
    public List<Dept> getDeptExceptSon(String deptid) {
        Dept dept = new Dept();
        dept.setDeptid(deptid);
        // 1.先查出根节点
        Dept rootDept = baseMapper.selectTopDept(dept);
        // 2.根据根节点查出所有后代节点
        List<Dept> allDepts = baseMapper.selectOffspringByDeptid(rootDept);
        // 3.查出该部门所有子代节点
        List<Dept> sonDepts = baseMapper.selectOffspringByDeptid(dept);

        if (rootDept.getDeptid().equals(dept.getDeptid())) {
            allDepts.clear();
            allDepts.add(rootDept);
        } else {
            for (int i = allDepts.size() - 1; i > 0; i--) {
                for (int j = sonDepts.size() - 1; j > 0; j--) {
                    String deptidi = allDepts.get(i).getDeptid();
                    String deptidj = sonDepts.get(j).getDeptid();
                    if (deptidi.equals(deptidj)) {
                        allDepts.remove(i);
                    }
                }
            }
        }

        return allDepts;

    }

//    @DS("adm-ds")
//    @Override
//    public <T> int updateByPk(T parameter) {
//        return super.updateByPk(parameter);
//    }

    /**
     * 该部门的子部门
     *
     * @return
     */

    @DS("adm-ds")
    public List<Dept> getChildrenDept(String deptid) {
        Dept dept = new Dept();
        dept.setDeptid(deptid);
        Map<String, Object> condition = new HashMap<>();
        condition.put("deptid", deptid);
        // 判断该部门是否有子部门
        List<Dept> deptList = baseMapper.selectChildrenByDeptid(dept);
        return deptList;
    }

    /**
     * 根据deptid获取该部门下的员工
     *
     * @return
     */

    @DS("adm-ds")
    public List<Map<String, Object>> getDeptMember(String deptid) {
        Map<String, Object> condition = new HashMap<String, Object>();
        // 查询该部门下的员工
        condition.put("deptid", deptid);
//        List<Map<String, Object>> rootMember = this.selectList("selectListByDepartId", condition);
        List<Map<String, Object>> rootMember = baseMapper.selectListMapByWhere(null, null, condition);
        for (int i = 0; i < rootMember.size(); i++) {
            if (rootMember.get(i).get("HEADIMGURL") == null) {
                rootMember.get(i).put("HEADIMGURL", rootMember.get(i).get("THEADIMGURL"));
            }
        }
        return rootMember;
    }

    /**
     * 根据所选择的deptid获取这些部门下的员工，包括子部门 的员工
     *
     * @return
     */

    @DS("adm-ds")
    public List<Map<String, Object>> getAllMember(List<GroupDept> deptList) {
        Map<String, Object> deptMap = new HashMap<>();
        for (Iterator iterator = deptList.iterator(); iterator.hasNext(); ) {
            GroupDept groupDept = (GroupDept) iterator.next();
            deptMap.put(groupDept.getDeptid(), groupDept);
        }
        for (int i = 0; i < deptList.size(); i++) {
            Dept deptCondition = new Dept();
            deptCondition.setDeptid(deptList.get(i).getDeptid());
            //找出所有子部门包括孙子部门:去除重复的部门
            List<Dept> allDepts = baseMapper.selectOffspringByDeptid(deptCondition);
            for (Iterator iterator = allDepts.iterator(); iterator.hasNext(); ) {
                Dept dept = (Dept) iterator.next();
                deptMap.put(dept.getDeptid(), null);
            }
        }

        //找到这所有部门下的所有员工。
        List<Map<String, Object>> deptMembers = new ArrayList<>();
        Set<String> keySet = deptMap.keySet();
        for (Iterator iterator = keySet.iterator(); iterator.hasNext(); ) {
            String deptid = (String) iterator.next();
            deptMembers.addAll(this.getDeptMember(deptid));
        }
        return deptMembers;


	/*	List<GroupDept> allDeptid=new ArrayList<>();
		allDeptid.addAll(deptList);
		for(int i=0;i<deptList.size();i++){
			Dept dept=new Dept();
			dept.setDeptid(deptList.get(i).getDepartId());
			//找出所有子部门包括孙子部门:去除重复的部门
			List<Dept> allDepts = this.selectList("selectOffspringByDeptid", dept);
			for(int j=0;j<allDepts.size();j++){
				int flag=0;
				for(int k=0;k<allDeptid.size();k++){
					if(allDepts.get(j).getDeptid().equals(allDeptid.get(k).getDepartId())){
						flag=1;
					}
				}
				if(flag==0){
					allDeptid.add(allDepts.get(j));
				}
			}
		}*/


    }

    /**
     * 获取根部门
     *
     * @return
     */

    @DS("adm-ds")
    public Dept getRootDeptInfo() {
        Dept dept = new Dept();
        Dept rootDept = new Dept();
        User user = LoginUtils.getCurrentUserInfo();
        dept.setDeptid(user.getDeptid());
        // 查询最顶级部门
        rootDept = baseMapper.selectTopDept(dept);
        return rootDept;
    }

    @DS("adm-ds")
    public Dept selectTopDept(Dept dept) {
        return baseMapper.selectTopDept(dept);
    }

    @DS("adm-ds")
    public List<Map<String, Object>> selectUserByDeptId(Dept dept) {
        return baseMapper.selectUserByDeptId(dept);
    }

}

